package com.mengwen.backstage.controller;

import com.mengwen.backstage.config.WeChatConfig;
import com.mengwen.backstage.pojo.Partner;
import com.mengwen.backstage.pojo.TransfersDto;
import com.mengwen.backstage.pojo.TransfersResult;
import com.mengwen.backstage.pojo.Withdraw;
import com.mengwen.backstage.service.PartnerService;
import com.mengwen.backstage.service.WithdrawService;
import com.mengwen.backstage.util.JwtUtil;
import com.mengwen.backstage.util.WechatpayUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author LiangYonghui
 * @date 2020/4/7 15:44
 * @description 提现
 */
@Controller
public class TransfersController {
    private static final Log LOG = LogFactory.getLog(TransfersController.class);

    @Autowired
    private WeChatConfig weChatConfig;

    @Autowired
    private PartnerService partnerService;

    @Autowired
    private WithdrawService withdrawService;

    @PostMapping("/transfers")
    public String transfers(@RequestParam("partner_token") String partnerToken, Model modelview) {
        Claims claims = JwtUtil.checkJWT(partnerToken);
        String role = (String) claims.get("role");
        String openid = (String) claims.get("partnerOpenid");
        String partnerNickname = (String) claims.get("partnerNickname");
        String partnerUnionid = (String) claims.get("partnerUnionid");
        if ("partner".equals(role) && (null != openid)&& (null != partnerNickname)&& (null != partnerUnionid)) {
            Partner partner;
            partner = partnerService.findByOpenid(openid);
            BigDecimal money = partner.getMoney();
            double amount = money.doubleValue();
            String appkey = weChatConfig.getKey();// 微信商户秘钥, 根据实际情况填写
            String certPath = weChatConfig.getCertPath();// 微信商户证书路径, 根据实际情况填写
            TransfersDto model = new TransfersDto();// 微信接口请求参数, 根据实际情况填写
            model.setMch_appid(weChatConfig.getAppId()); // 申请商户号的appid或商户号绑定的appid
            model.setMchid(weChatConfig.getMchId()); // 商户号
            model.setMch_name("萌问趣答"); // 商户名称
            model.setOpenid(openid); // 商户appid下，某用户的openid
            model.setAmount(amount); // 企业付款金额，这里单位为元
            model.setDesc("测试企业付款到零钱"); // 描述
            String PartnerTradeNo = model.getMchid()
                    + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                    + (int)((Math.random() * 9 + 1) * 1000);
            model.setPartner_trade_no(PartnerTradeNo);
            // 微信官方API文档 https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
            TransfersResult transfersResult = WechatpayUtil.doTransfers(appkey, certPath, model);
            if (transfersResult.isSuccess()) {
                // 添加提现成功的订单
                BigDecimal reset = new BigDecimal(0);
                partner.setMoney(reset);
                Withdraw withdraw = new Withdraw();
                withdraw.setAmount(money);
                withdraw.setDesc("测试企业付款到零钱");
                withdraw.setOpenid(openid);
                withdraw.setNickname(partnerNickname);
                withdraw.setPartnerTradeNo(PartnerTradeNo);
                Integer addTerm = withdrawService.addTerm(withdraw);
                if (addTerm < 0) {
                    LOG.error("提现成功，但向数据库插入信息失败。订单号：" + PartnerTradeNo);
                }
                LOG.info(transfersResult);
                // 将数据库的money置成0
                int update = partnerService.updateMoneyByopenid(openid);
                if (update < 0) {
                    LOG.error("提现成功，但数据库更新失败。订单号：" + PartnerTradeNo + "openid:" + openid);
                }
            }else {
                LOG.info("提现失败，openid:" + openid);
            }


            modelview.addAttribute("partner",partner);
            // 分发jwttoken
            String newPartnerToken = JwtUtil.genePartnerJsonWebToken(partner);
            modelview.addAttribute("partnerToken",newPartnerToken);
            return "partner_page";
        } else {
            // 无权限执行提现
            System.out.println("无权限执行提现");
//            return new TransfersResult(false);
            return "login_door";
        }


    }
}